const mongoose = require('mongoose')
const tools = require('./tools')
const Schema = mongoose.Schema
const Question = {}


const questionSchema = Schema({
    text: {
        type: String,
        required: [true, '请填写问题内容！'],
        minlength: [5, '问题内容至少5个字符！'],
        maxlength: [100, '问题内容最多100个字符！']
    },
    keyword: {
        type: String,
        required: [true, '请选择关键词！'],
        minlength: [3, '关键词至少3个字符！'],
        maxlength: [20, '关键词最多20个字符！']
    },
    createUser: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    createTime: Date,
    ip: String,
    answers: [{
        type: Schema.Types.ObjectId,
        ref: 'answers'
    }]
})


Question.Model = mongoose.model('questions', questionSchema)


Question.getById = function (id) {
    return new Promise(function (resolve, reject) {
        Question.Model.findById(id)
            .populate({
                path: 'createUser',
                select: '-password'
            })
            .populate({
                path: 'answers',
                populate: {
                    path: 'createUser',
                    select: '-password'
                }
            })
            .exec((err, model) => {
                if (err) {
                    reject(err)
                }
                else {
                    resolve(tools.toData(model))
                }
            })
    })
}


Question.listByPager = function (filter, pageNo = 1, pageCount = 20) {
    if (pageNo < 1) throw new RangeError('参数 pageNo 不应小于 1。')
    if (pageCount < 1) throw new RangeError('参数 pageCount 不应小于 1。')

    return new Promise(function (resolve, reject) {
        Question.Model.find(filter)
            .sort('-createTime')
            .skip((pageNo - 1) * pageCount)
            .limit(pageCount)
            .populate({
                path: 'createUser',
                select: '-password'
            })
            .populate({
                path: 'answers',
                populate: {
                    path: 'createUser',
                    select: '-password'
                }
            })
            .exec((err, models) => {
                if (err) {
                    reject(err)
                }
                else {
                    resolve(tools.toDatas(models))
                }
            })
    })
}


module.exports = Question
